package com.whu.MenuHub.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whu.MenuHub.dao.ReceivingAddressDao;
import com.whu.MenuHub.domain.ReceivingAddress;
import com.whu.MenuHub.exception.MenuHubException;
import com.whu.MenuHub.service.AddressService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<ReceivingAddressDao, ReceivingAddress> implements AddressService {
    @Autowired
    ReceivingAddressDao addressDao;

    //根据用户id获取所有收获地址信息
    @Cacheable(cacheNames = "address",key = "#userid",condition = "#userid!=null")
    @Override
    public List<ReceivingAddress> getaddressByUserID(Integer userid){
        QueryWrapper<ReceivingAddress> qw = new QueryWrapper<>();
        //查询price这列大于一定数值的记录
        qw.eq("userID", userid);
        return addressDao.selectList(qw);
    }

    //新增地址后需要返回所有的数据
    @CacheEvict(cacheNames = "address",key = "#address.userID")
    //新增一条收获地址信息
    @Override
    public ReceivingAddress insertAddress(ReceivingAddress address) throws MenuHubException {
        try{
            addressDao.insert(address);
            return address;
        }catch (Exception e){
            throw new MenuHubException(MenuHubException.ErrorType.INSERT_ERROR,"添加地址信息失败");
        }
    }

    //更新一条收获地址信息
    @Override
    @CacheEvict(cacheNames = "address",key = "#address.userID")
    public void updateAddress(ReceivingAddress address) throws MenuHubException{
        try{
            addressDao.updateById(address);
        }catch (Exception e){
            throw new MenuHubException(MenuHubException.ErrorType.UPDATE_ERROR,"修改地址信息失败");
        }
    }

    @Override
    public ReceivingAddress getAddressByID(Integer id) {
        return addressDao.selectById(id);
    }

    //删除一条收获地址信息，这里将userID作为参数，是因为要删除缓存中的信息
    @Override
    @CacheEvict(cacheNames = "address",key = "#userID")
    public void deleteAddressById(Integer id, Integer userID) throws MenuHubException{
        try{
            addressDao.deleteById(id);
        }catch (Exception e){
            throw new MenuHubException(MenuHubException.ErrorType.DELETE_ERROR,"删除地址信息失败");
        }
    }

    //获取用户的默认地址
    @Override
    @CacheEvict(cacheNames = "defaultAddress",key = "#userID")
    public ReceivingAddress getDefaultAddress(Integer userID){
            return addressDao.getDefaultAddress(userID);

    }

}
